package controller;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Iterator;

import javax.swing.AbstractAction;
import javax.swing.JFrame;

import model.Adressbook;
import model.Contact;
import view.AddcontactView;

/**
 * 
 * @author Nelly-Kim TRAN
 * 
 * allows to add a contact in the set of contacts and in the file that store all the data
 * 
 * @param frame
 * 			keeps the previous frame in store to close it afterwards
 *
 */

public class AddcontactListener implements ActionListener{
	
	private AddcontactView frame;

	public AddcontactListener(AddcontactView f) {
		this.frame=f;
	}
	
	public void actionPerformed(ActionEvent e) {
		
		//Adding the new contact to the set 
		Adressbook.contacts.add(new Contact(frame.firstname.getText(),frame.lastname.getText(), frame.homeaddress.getText(), frame.companyaddress.getText(),
				frame.personalmobile.getText(), frame.personalhome.getText(), frame.professionnalmobile.getText(), frame.professionnaloffice.getText(),
				frame.homepage.getText(), frame.professionnalemail.getText(), frame.personnalemail.getText(), frame.photo.getText(), frame.group.getText()));
		
		//Adding the new contact to the file ( erase and rewrite the contacts stored in the set)
			try{
				File yourFile = new File("monfichier2.txt");
				yourFile.delete();
				File yourNewFile = new File("monfichier2.txt");
				yourNewFile.createNewFile(); 
				
				PrintStream l_out = new PrintStream(new FileOutputStream("monfichier2.txt",true));	
				Iterator j=Adressbook.contacts.iterator();
				while(j.hasNext()) {
					Contact c=(Contact)j.next();
					l_out.print(c.getFirstname()+ ","); 
					l_out.print(c.getLastname()+","); 
					l_out.print(c.getHomeaddress()+","); 
					l_out.print(c.getCompanyaddress()+","); 
					l_out.print(c.getPersonalmobile()+","); 
					l_out.print(c.getPersonalhome()+","); 
					l_out.print(c.getProfessionnalmobile()+","); 
					l_out.print(c.getProfessionnaloffice()+","); 
					l_out.print(c.getHomepage()+","); 
					l_out.print(c.getPersonalemail()+","); 
					l_out.print(c.getProfessionalemail()+","); 
					l_out.print(c.getPhoto()+","); 
					l_out.print(c.getGroup()+"\r\n"); 
				}
				
		
				l_out.flush(); 
				l_out.close(); 
				l_out=null; 
			}
		
			catch (Exception exc) {System.out.println("problem with txt file");}
		
	}
	

}

